package com.le.basic.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 二叉树的序列化和反序列化
 */
public class Code_04_SerializeAndReconstructTree {
    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    /**
     * 二叉树先序序列化
     * @param head
     * @return
     */
    public static String serialByPre(Node head) {
        if (head == null) {
            return "#!";
        }
        String res = head.value + "!";
        res += serialByPre(head.left);
        res += serialByPre(head.right);
        return res;
    }

    /**
     * 反序列化
     * @param preStr
     * @return
     */
    public static Node reconByPreString(String preStr) {
        String[] split = preStr.split("!");
        Queue<String> queue = new LinkedList<>();
        for (int i = 0; i < split.length; i++) {
            queue.offer(split[i]);
        }

        return reconPreOrder(queue);
    }

    public static Node reconPreOrder(Queue<String> queue) {
        String val = queue.poll();
        if (val.equals("#")) {
            return null;
        }
        Node head = new Node(Integer.valueOf(val));
        head.left = reconPreOrder(queue);
        head.right = reconPreOrder(queue);
        return head;
    }

    public static void preOrderRecur(Node head){
        if (head == null){
            return;
        }
        System.out.print(head.value + "  ");
        preOrderRecur(head.left);
        preOrderRecur(head.right);
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        head.right.right = new Node(7);
        String s = serialByPre(head);
        Node node = reconByPreString(s);
        preOrderRecur(node);
    }
}
